/*
 * Copyright 2011 Michele Mancioppi [michele.mancioppi@gmail.com]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cave.nice.testMessage.cron;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;

import cave.nice.testMessage.TestMessageConstants;
import cave.nice.testMessage.data.CannotRetrieveEntitiesException;
import cave.nice.testMessage.data.DataManager;
import cave.nice.testMessage.data.VerifiedAccount;
import cave.nice.testMessage.reports.ReportsGenerator.ReportType;
import cave.nice.testMessage.reports.ReportsGenerator.ReportingMedium;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

@SuppressWarnings("serial")
public class CheckTestsServlet extends HttpServlet {

	private static final Logger LOGGER = Logger
			.getLogger(CheckTestsServlet.class.getName());

	private Queue tasksQueue = null;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);

		tasksQueue = QueueFactory.getQueue(TestMessageConstants.REPORTING_TASKS_QUEUE_NAME);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		DataManager dataStoreManager = DataManager.getInstance();

		try {
			DateTime currentTime = dataStoreManager.getCurrentTime();
			List<VerifiedAccount> accounts = dataStoreManager.getVerifiedAccounts();
			for (VerifiedAccount account : accounts) {
				/*
				 * TODO Use account-specific configurations
				 */
				tasksQueue
						.add(TaskOptions.Builder
								.withUrl("/resources/accounts/" + account.getEmailAddress() + "/reportRequest")
								.param("type", ReportType.TEXT_PLAIN.toString()).param("medium", ReportingMedium.GTalk.toString()));
			}
			LOGGER.info("Round of checks started at " + currentTime);
		} catch (CannotRetrieveEntitiesException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			dataStoreManager.close();
		}
	}

}
